<template>
  <div class="tiny-fullscreen-scroll">
    <div class="tiny-fullscreen-wrapper">
      <div class="user-add-btn">
        <tiny-button v-permission="'company::add'" type="primary" @click="handleAddCompany">新增公司'
        </tiny-button>
      </div>
      <div class="table">
        <tiny-grid ref="grid" :fetch-data="fetchDataOption" :pager="pagerConfig" :auto-resize="true" remote-filter>
          <tiny-grid-column type="index" width="30"></tiny-grid-column>
          <tiny-grid-column :title="'公司名称'">
            <template #default="data">
              <span>{{ data.row.name }}</span>
            </template>
          </tiny-grid-column>
          <tiny-grid-column :title="'公司简称'">
            <template #default="data">
              <span>{{ data.row.short_name }}</span>
            </template>
          </tiny-grid-column>
          <tiny-grid-column :title="'法人姓名'">
            <template #default="data">
              <span>{{ data.row.legal_person }}</span>
            </template>
          </tiny-grid-column>
          <tiny-grid-column :title="'联系电话'">
            <template #default="data">
              <span>{{ data.row.telephone }}</span>
            </template>
          </tiny-grid-column>
          <tiny-grid-column :title="'公司地址'">
            <template #default="data">
              <span>{{ data.row.address }}</span>
            </template>
          </tiny-grid-column>
          <tiny-grid-column :title="'收货地址'">
            <template #default="data">
              <span>{{ data.row.delivery_address }}</span>
            </template>
          </tiny-grid-column>
          <tiny-grid-column :title="'邮政编码'">
            <template #default="data">
              <span>{{ data.row.post_code }}</span>
            </template>
          </tiny-grid-column>
          <tiny-grid-column :title="'注册资本'">
            <template #default="data">
              <span>{{ data.row.registered_capital }}</span>
            </template>
          </tiny-grid-column>
          <tiny-grid-column :title="'银行账号'">
            <template #default="data">
              <span>{{ data.row.account }}</span>
            </template>
          </tiny-grid-column>
          <tiny-grid-column :title="'联行号'">
            <template #default="data">
              <span>{{ data.row.line_number }}</span>
            </template>
          </tiny-grid-column>
          <tiny-grid-column :title="'开户行名称'">
            <template #default="data">
              <span>{{ data.row.bank_name }}</span>
            </template>
          </tiny-grid-column>
          <tiny-grid-column :title="'操作'" align="center">
            <template #default="data">
              <a v-permission="'company::update'" class="operation-update" @click="handleUpdate(data.row)">
                修改
              </a>
              <a v-permission="'company::del'" class="operation-delete" @click="handleDelete(data.row.id)">
                删除
              </a>
            </template>
          </tiny-grid-column>
        </tiny-grid>
      </div>
    </div>
  </div>
  <div v-if="state.isCompanyAdd">
    <tiny-modal 
      v-model="state.isCompanyAdd" 
      :lock-scroll="true" 
      mask-closable="true" 
      height="auto" 
      width="800"
      :title="新增公司"
    >
      <!-- 监听 confirm 事件 -->
      <CompanyAdd @confirm="onAddConfirm"></CompanyAdd>
    </tiny-modal>
  </div>
  <div v-if="state.isCompanyUpdate">
    <tiny-modal 
      v-model="state.isCompanyUpdate" 
      :lock-scroll="true" 
      mask-closable="true" 
      height="auto" 
      width="800"
      :title="'修改公司基本信息'"
    >
      <CompanySetting 
        :companyData="state.rowDate" 
        @cancel="onUpdateCancel" 
        @confirm="onCompanyUpdateConfirm"
      >
      </CompanySetting>
    </tiny-modal>
  </div>
</template>
  
<script lang="ts" setup>
  import { reactive, computed, ref } from 'vue';
  import { useI18n } from 'vue-i18n';
  import {
    GridColumn as TinyGridColumn,
    Grid as TinyGrid,
    Pager as TinyPager,
    Modal as TinyModal,
    Button as TinyButton,
  } from '@opentiny/vue';
  import { useUserStore } from '@/store';
  import { addCompany, deleteCompany, getAllCompany, transformCompany} from '@/api/company';
  import { useRouter } from 'vue-router';
  import { FilterType } from '@/types/global';
  import CompanyAdd from '../../companyadd/index.vue';
  import CompanySetting from '../../setting/index.vue';

  const router = useRouter();
  const grid = ref();
  const activeName = ref('first');
  const renderOp = ref({
    field: 'area'
  });

  // 加载效果
  const state = reactive<{
    loading: any;
    tableData: any;
    pageData: any;
    isCompanyAdd: boolean;
    isCompanyUpdate: boolean;
    rowDate: any;
    info:any;
  }>({
    loading: null,
    tableData: [] as any,
    pageData: [] as any,
    isCompanyAdd: false,
    isCompanyUpdate: false,
    rowDate: '',
    info:'',
  });

  // 变量设置  
  const pagerConfig = reactive({
    component: TinyPager,
    attrs: {
      currentPage: 1,
      pageSize: 10,
      pageSizes: [5, 10, 15, 20],
      total: 10,
      layout: 'total, prev, pager, next, jumper, sizes',
    },
  });


  // 请求数据接口方法
  const fetchData = async (
    params: { pageIndex: 1; pageSize: 10 },
    filters: FilterType,
  ) => {
    try {
      // 传递参数调用 getAllCompany
      const { data } = await getAllCompany(params.pageIndex,
        params.pageSize,
        filters,);
      
      // 检查 data 和 data.meta 是否存在
      const total = data && data.meta? data.meta.totalItems : 0;
      
      const result = data? data.items || [] : [];
      
      const result1 = result.slice((params.pageIndex-1)*params.pageSize,(params.pageIndex)*params.pageSize);

      return {
        result: result1,
        page: { total },
      };
    } catch (error) {
      console.error('获取数据失败:', error);
      return {
        result: [],
        page: { total: 0 },
      };
    }
  };

  const fetchDataOption = reactive({
    api: ({ page, filters }: any) => {
      const { currentPage, pageSize } = page; 
      return fetchData(
        {
          pageIndex: currentPage,
          pageSize,
        },
        filters,
      );
    },
    filter: true,
  });

  const onUpdateCancel = () => {
    state.isCompanyUpdate = false;
  };
  
  const onCompanyUpdateConfirm = async () => {
    grid.value.handleFetch().then(() => {
      state.isCompanyUpdate = false;
    });
  };

  const onCompanyinfo = async () => {
    grid.value.handleFetch().then(() => {
      state.isCompanyUpdate = false;
    });
  };


  const onAddConfirm = async (proj) => { 
    addCompany(proj).then(({ data }) => { 
      TinyModal.message({
        message: '新增公司成功',
        status: 'success',
      });
      data.value.push({
        name: data.name,
        short_name: data.short_name,
        legal_person: data.legal_person,
        telephone: data.telephone,
        address: data.address,
        delivery_address: data.delivery_address,
        post_code: data.post_code,
        registered_capital: data.registered_capital,
        account: data.account,
        line_number: data.line_number,
        bank_name: data.bank_name,
      });
      grid.value.handleFetch();
    }) 
    .catch((error) => {
      if (error.response && error.response.data) {
        const errorMessage = error.response.data.message || '未知错误';
        TinyModal.message({
          message: errorMessage,
          status: 'error',
        });
      }
    })
    .finally(() => {
      grid.value.handleFetch();
      state.isCompanyAdd = false; // 将控制 CompanyAdd 页面显示的状态变量设置为 false
    });
  };

  const handleDelete = async (id: number) => {
    TinyModal.confirm(`删除公司，将同时删除该公司所有相关信息，确定删除吗？`).then((result) => {
      if (result === 'confirm') {
        deleteCompany(id).then((res) => {
          TinyModal.message({
            message: '已删除',
            status: 'success',
          });
          grid.value.handleFetch();
        })
        .catch((error) => {
          if (error.response && error.response.data) {
            const errorMessage = error.response.data.message || '未知错误';
            TinyModal.message({
              message: errorMessage,
              status: 'error',
            });
          }
        });
      }
    });
  };

  const handleUpdate = (row: any) => {
    state.isCompanyUpdate = true;
    state.rowDate = transformCompany(row);
  };

  const handleAddCompany = () => {
    state.isCompanyAdd = true;
  };
</script>
  
<style scoped lang="less">
  .companyadd-add-btn {
    padding: 10px 0 10px 10px;
  }

  #contain {
    height: 100%;
    padding: 15px;
    overflow: hidden;
  }

  .table {
    padding-bottom: 20px;
    background-color: #fff;
  }

  .operation {
    &-update {
      color: orange;
    }

    &-delete {
      padding-right: 5px;
      color: red;
    }

    &-pwd-update {
      padding-right: 5px;
      color: #1890ff;
    }


  }

  .pc-demo .tiny-tabs__content {
    line-height: 2;
  }

  .equal-width-table {
  border-collapse: collapse;
  width: 100%;
}

.equal-width-table td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
}
</style>

  